<?php

namespace App\Repository\UpThree;

use App\Api\CatchOrder\DouYin;
use App\Api\Three\DouYinOld;
use App\Jobs\OrderSubmit;
use App\Repository\BaseRepository;
use App\Repository\CatchConf\DouYinCatchRepository;
use App\Repository\CatchConf\DouYinRepository;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class GetThreeOrderRepostition_back extends BaseRepository
{
    public function __construct()
    {
        $this->log = new Logger('ChinnelLog');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    public function getOrder($data)
    {
        if (empty($data['type'])) {
            return $this->returnMsg(11, '类型为空');
        }
        $type = $data['type'];
        $return = [];
        switch ($type) {
            case 'douyin':
                $return = $this->getDouYinOrder($data);
                break;
        }
        return $return;
    }

    // 获取订单 通过订单详情获取抖音的数据
    public function getDouYinOrder($data = array())
    {

        // 根据推送过来的信息 获取订单详情 需要对接
        if (empty($data['shop_id'])) {
            return $this->returnMsg(103, '抖音信息为空');
        }
        $douyinRModel = new DouYinRepository();
        $whereDouYin = [
            'app_shop_id' => $data['shop_id'],
            'nums' => 1
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);
        // var_dump($resDouYin);
        // die();
        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询抖音配置');
        }
        // 查询抖音的数据
        $douyinModel = new DouYin($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret);
        if (!empty($data['pid'])) {
        }
        $resDouYinDetails = $douyinModel->orderDetails($data);
        // var_dump($resDouYinDetails, 1111111111);
        if (empty($resDouYinDetails['data'][0])) {
            return $this->returnMsg(200, '未查询到订单信息');
        }
        $disUserId = '';
        $disUserName = '';
        // die();
        $resDouYinDetail = $resDouYinDetails['data'][0];
        if (!empty($resDouYinDetail['author_id'])) {
            $whereDis = [
                ['supplier_id', '=', $resDouYin->id],
                ['dist_code', 'like', '%,' . $resDouYinDetail['author_id'] . ',%'],
            ];
            $disArr = DB::table('supplier')->where($whereDis)->field('name,shop_id')->first();
            if ($disArr) {
                $disUserId = $disArr->shop_id;
                $disUserName = $disArr->name;
            }
        }
        // 代理的订单的话 来源是 6 别的来源是 1
        $orderData = [
            'source' => !empty($disUserId) ? 6 : 1,  // 数据来源
            'goods_code' => $resDouYinDetail['product'],
            'name' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_name'] : '',
            'identity' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['card_num'] : '',
            'contact' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_phone'] : '',
            'province' => $resDouYinDetail['province'],
            'city' => $resDouYinDetail['city'],
            'area' => $resDouYinDetail['area'],
            'address' => (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . (($resDouYinDetails['code'] == 200) ? $resDouYinDetail['addr'] : ''),
            'shop_id' => $resDouYin->shop_id,
            'dist_orderno' => $resDouYinDetail['order_num'],
            'dist_id' => !empty($disUserId) ? $disUserId : '',
            'dist_name' => !empty($disUserName) ? $disUserName : '',
            'author_id' => $resDouYinDetail['author_id'],
            'author_name' => $resDouYinDetail['author_name'],
            'remark' => $resDouYinDetail['c_biz_desc'],
            'douyin_id' => $resDouYin->id, //代理信息
            'douyin_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '', //代理名称
        ];
        // 存入到订单表中
        $res = [];
        $orderData['status'] = 51;
        if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            $model = new MainOrderRepostition();
            $res = $model->orderSubmit($orderData);
            $orderData['status'] = 0;
        }
        $orderData['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $orderData['status'] = 60;
        }
        $orderData['package_name'] = !empty($resDouYinDetail['package_name']) ? $resDouYinDetail['package_name'] : '';
        $orderData['created_at'] = !empty($resDouYinDetail['created_at']) ? $resDouYinDetail['created_at'] : '';
        $orderData['douyin_status_name'] = !empty($resDouYinDetail['douyin_status_name']) ? $resDouYinDetail['douyin_status_name'] : '';
        $models = new DouYinCatchRepository();
        $insertData = $models->add($orderData);
        // 需要提交到 老系统的抖音里面
        if (!empty($insertData['data']['id'])) {
            dispatch(new OrderSubmit($insertData['data']['id'], 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
            // 判断提交时间 48小时限制 抖店的订单
            //strtotime(date('Y-m-d 09:00:00', strtotime('+1 days')))
            $times = 46 * 60 * 60; // 默认 46h后 处理
            dispatch(new OrderSubmit($orderData['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
        }

        return $res;
    }

    //抖音漏单抓取 将抓取的抖音数据抓取 存入数据表
    public function getMissingOrder($page = 0)
    {
        // var_dump($page, 999999999999);
        $page = 0;
        $nums = 10;
        // DB::connection()->enableQueryLog();
        $data = DB::table('dd_no_submit_order')->where('is_back', 0)->skip($page * $nums)->take($nums)->get();
        // $sql = DB::getQueryLog();
        // var_dump($sql);
        if (!empty($data)) {
            foreach ($data as $key => $v) {
                $disUserId = '';
                $disUserName = '';
                $v = json_decode(json_encode($v), true);
                $shopRes = DB::table('douyin_conf')->where('app_shop_id', $v['shop_id'])->first();
                if (!$shopRes) {
                    continue;
                }
                if (!empty($v['author_id'])) {
                    $whereDis = [
                        ['supplier_id', '=', $shopRes->shop_id],
                        ['dist_code', 'like', '%,' . $v['author_id'] . ',%'],
                    ];
                    $disArr = DB::table('supplier')->where($whereDis)->select(['name', 'shop_id'])->first();
                    if ($disArr) {
                        $disUserId = $disArr->shop_id;
                        $disUserName = $disArr->name;
                    }
                }
                $data = [
                    'source' => !empty($disUserId) ? 6 : 1,  // 数据来源
                    'goods_code' => $v['product'],
                    'name' => $v['user_name'],
                    'identity' => $v['card_num'],
                    'contact' => $v['user_phone'],
                    'province' => $v['province'],
                    'city' => $v['city'],
                    'area' => $v['area'],
                    'address' => (!empty($v['street']) ? $v['street'] : '') . ($v['addr']),
                    'shop_id' => $shopRes->shop_id,
                    'dist_orderno' => $v['order_num'],
                    'dist_id' => !empty($disUserId) ? $disUserId : '',
                    'dist_name' => !empty($disUserName) ? $disUserName : '',
                    'author_id' => $v['author_id'],
                    'author_name' => $v['author_name'],
                    'remark' => $v['c_biz_desc'],
                    'douyin_id' => $shopRes->id, //抖音信息
                    'douyin_name' => !empty($shopRes->remark) ? $shopRes->remark : '', //抖音店铺名称
                ];
                $res = $this->handleData($data);
                if ($res) {
                    DB::table('dd_no_submit_order')->where('id', $v['id'])->update(['is_back' => 1]);
                }
            }
            $page += 1;
        }
        if (empty($data) || count($data) < $nums) {
            $page = 0;
        }

        if ($page > 0) {
            $this->getMissingOrder($page);
        }
        return 1;
    }

    // 抖音单条数据处理 存入到表中
    public function handleData($data = [])
    {
        $model = new DouYinCatchRepository();
        $where = [
            'dist_orderno' => $data['dist_orderno'],
        ];
        //查询某个数据是否存在
        $res = $model->getOne($where);
        if ($res) {
            if (!empty($res->contact)) {
                // var_dump($where);
                return 1;
            }
            $update = $model->edit($where, $data);
            // 将本地系统的数据重新推送到第三方
            dispatch(new OrderSubmit($where['dist_orderno'], 'createOrder'))->onQueue('TaskOrderSubmitDispose');
            // 推送到老系统的订单
            dispatch(new OrderSubmit($res->id, 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
            // 判断提交时间 48小时限制 抖店的订单  订单数据处理
            $times = 46 * 60 * 60; // 默认 46h后 处理
            dispatch(new OrderSubmit($data['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
            return $update;
        }
        // 存入到订单表中
        $res = [];
        $data['status'] = 51;
        if (true) {
            // 本地信息推送
            $data['shop_id'] = $data['dist_id'];
            $models = new MainOrderRepostition();
            $res = $models->orderSubmit($data);
            var_dump($res, 111111111);
            $data['status'] = 0;
        }
        $data['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $data['status'] = 60;
        }
        $insertData = $model->add($data);
        if (!empty($insertData['data']['id'])) {

            dispatch(new OrderSubmit($insertData['data']['id'], 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
            // 判断提交时间 48小时限制 抖店的订单
            //$times = 46 * 60 * 60; // 默认 46h后 处理
            //dispatch(new OrderSubmit($data['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
        }
        return 1;
    }

    // 推送到老系统
    public function catchDouYinOld($data)
    {
        $model = new DouYinOld();
        $where = [
            'dist_orderno' => $data['orderno']
        ];
        return $model->orderSubmit($where);
    }

    //以防漏单的数据处理  四个小时 抓取一次
    public function getMissingOrderAll($page = 0)
    {
        $nums = 10;
        $createTime = strtotime("-5 hours");
        $endTime = time();
        $datas = DB::table('douyin_conf')->where('nums', 1)->take($page * $nums)->skip($nums)->get();
        if (empty($datas) || count($datas) < $nums) {
            $page = 0;
        }
        foreach ($datas as $key => $v) {
            //发送之前先看下是否都是数字
            if (empty($v->app_shop_id) || !is_numeric($v->app_shop_id)) {
                continue;
            }
            if (empty($v->app_key) || !is_numeric($v->app_key)) {
                continue;
            }
            $model = new DouYin($v->app_shop_id, $v->app_key, $v->app_secret);
            $model->orderList($page, $createTime, $endTime);
        }
    }
}
